﻿CREATE PROCEDURE [acms].[Post_GetAllByParentId]
	@ParentId int,
	@VersionTimeStamp datetime
AS
	if(@VersionTimeStamp is null) begin
		declare @tmp table (PostId int, VersionId int)
		
		insert into @tmp (PostId, VersionId)
		SELECT Id, VersionId
		FROM [Post_View]
		Where ParentId = @ParentId
			and StartDate is null
			and EndDate is null

		insert into @tmp (PostId, VersionId)
		SELECT Id, VersionId
		FROM [Post_View]
		Where ParentId = @ParentId
			and StartDate is not null
			and EndDate is null
			and Id not in (Select PostId from @tmp)
		
		select a.* 
		from [Post_View] a 
			inner join @tmp b on a.VersionId = b.VersionId
		order by a.Sequence

	end	
	else begin
		SELECT *
		FROM [Post_View]
		Where ParentId = @ParentId
			and StartDate <= @VersionTimeStamp
			and IsNull(EndDate, @VersionTimeStamp) >= @VersionTimeStamp
		ORDER By Sequence
	end
RETURN 0;